import web
import webbrowser
def my_loadhook():
    
    # webbrowser.open('www.frontarena.com')
    print "my load hook"

# create a load hook to move flash message from the session to the context 
web.session.flash = {} 
def flash_msg(): 
    # set the context flash message 
    web.ctx.flash = web.session.flash or {} 
    # clear the flash messages from the session 
    web.session.flash = {} 


#def my_unloadhook():
#    #1/0
#    print "my unload hook"
#    
#def my_processor(handler): 
#    print 'before handling'
#    result = handler() 
#    print 'after handling'
#    return result




urls = (
  '/', 'index',
  '/page', 'page',
  '/page/sub/','page',
  '/template', 'template',
  '/digitargs/(\d+)', 'digitargs',
  '/textargs/(\w+)', 'textargs',
  '/sessions/(\w+)', 'sessions',
  '/authenticate', 'authenticate',
  '/logout', 'logout'
)
web.config.debug = True # If 'True' sessions will stop working 
app = web.application(urls, locals()) #what's the diff between globals and locals here?

app.add_processor(web.loadhook(flash_msg)) 

# helper function to add new flash messages 
def flash(**kargs): 
    web.session.flash.update(kargs) 


#app.add_processor(my_processor)
#app.add_processor(web.loadhook(my_loadhook))
#app.add_processor(web.unloadhook(my_unloadhook))

# can use DBStore instead, but requires setup of table
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'msg':'hello 22','authenticated':0, 'username':'fred'})






class index:
    def GET(self):
        return '''
    <h3>A header</h3>
    <h1>Test plannning</h1>
    <h1>Home</h1>
    <a href = /page>Got to a page</a></br>
    <a href = /template>Got to a template</a></br>
    <a href = /digitargs/23>Digit args (change number) </a></br>
    <a href = /textargs/texty>Text args (change text) </a></br>
    <a href = /sessions/changethis>Sessions</a></br>
    <a href = /authenticate>authenticate</a></br>
    '''
class page:
    def GET(self):
        x = session
        # y = 1/0 # delib. error
        print "test print from page"
        # flash({'message':'fred'})
        text = str(web.ctx.flash) +  '<br />'
        text += str(session)
        return text
        # return  "<h1>A Page</h1><a href = />Go to home 1</a></br>" + str(session.store)
        
    
class template:
    def GET(self):
        render = web.template.render('template', base = 'base')
        # return render.template_1('world')
        session.msgx = 'test123'
        flash(message='Freddddd')
        web.seeother('/page')


class digitargs:
    def GET(self, arg):
            render = web.template.render('template', base = 'base')
            return render.template_1(arg)

class textargs:
    def GET(self, arg):
            render = web.template.render('template', base = 'base')
            return render.template_1(arg)

class sessions:
    def GET(self, arg):
        print 101
        oldmsg = session.msg
        session.msg ="start"
        session.msg = arg
        render = web.template.render('template', base = 'base')
        return render.template_1(oldmsg)

log_in = web.form.Form(
            web.form.Textbox("login", web.form.notnull, description="User name"),
            web.form.Password("password", web.form.notnull, description="Password")
        )
users = {"ml": "123", "jl":"456","abc":"abc" }
def logged(session):
    if "authenticated" in session:
        if session.authenticated == 1:
            return True
    return False

class authenticate:
        def GET(self):
            web.header("Content-Type","text/html; charset=utf-8")
            if logged(session):
                ret = "U logged as <b>%s</b>"%session.username
                return (ret + "<br /><a href='/'>Home</a>"
                        + "<br /><a href='/logout'>Logout</a>"
                        +"<br />" + session.username + " ### " + str(session.authenticated) )
            else:
                return ("<br /><a href='/'>Home</a>"
                        +"<br />Not logged in<br /> <form name='main' method='post'> "
                        + log_in.render() + "<input type='submit' />"
                         +"<br />" + session.username + " ### " + str(session.authenticated) )
        
        def POST(self):
            i = web.input()
            if i.login in users and users[i.login] == i.password:
                session.authenticated = 1
                session.username = i.login
            web.seeother("/authenticate")
            
class logout:
    def GET(self):
        session.authenticated = 0
        session.kill()
        web.seeother("/authenticate")

if __name__ == "__main__":
    print 1100
    app.run()

# print help(app.run)
# Path to this file:
# cd C:\Documents and Settings\merlov01\My Documents\SunGard\Python\owlspace\Tutorials\
# python home.py 8082
# http://localhost:8082 
